﻿using System;
using System.Web.Mvc;
using SecurityLog.Models;
using SecurityLog.Repositories;

namespace SecurityLog.Controllers
{
    public class LogViewController : Controller
    {
        //
        // GET: /LogView/
        private ILogRepository _logRepository;
        private IUsersRepository _userRepository;

        public LogViewController()
        {
            _logRepository = new LogRepository();
            _userRepository = new UsersRepository();
        }

        public LogViewController(ILogRepository logRepository, IUsersRepository usersRepository)
        {
            _logRepository = logRepository;
            _userRepository = usersRepository;
        }

        public ActionResult Index()
        {
            LogViewModel logViewModel = new LogViewModel();

            logViewModel.Log = _logRepository.GetCurrentLog(DateTime.Now.AddHours(-24));

            
            if (Request != null && Request.IsAjaxRequest())
                return Json(logViewModel, JsonRequestBehavior.AllowGet);
            
            logViewModel.CategoryList = _logRepository.GetCategoryList();
            return View(logViewModel);
        }

        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult Index(string newEntry, string User, string Password, int Category)
        {
            User user = _userRepository.GetUser(User, Password);

            if (user != null && user.Enabled)
            {
                Entry entry = new Entry();

                entry.Created = DateTime.Now;
                entry.Modified = DateTime.Now;
                entry.CategoryId = Category;
                entry.UserId = user.Id;
                entry.Body = newEntry;
                _logRepository.InsertEntry(entry);
                _logRepository.SaveChanges();

                return RedirectToAction("Index");
            }
            
            TempData["fail"] = "Either Username/password is incorrect, or user has been deactivated.";
            return RedirectToAction("Index");
        }

    }
}
